<template>
    <d2-container :filename="filename">
        <template slot="header">
            <el-form :inline="true" size="mini">
                <el-button type="primary" size="mini" icon="el-icon-plus"
                           @click="handleForm({'type':'DIR','open_type':'DEFAULT','sorted': '999','parentId':0, icon:'d2-crud'},'create')">
                    新增
                </el-button>

                <el-input size="mini" v-model="queryParam.name" placeholder="名称或编码"
                          style="width: 100px;margin-left: 10px;"/>
                <el-button size="mini" title="刷新" @click="getList" icon="el-icon-refresh" circle
                           style="margin-left: 5px;"></el-button>

            </el-form>
        </template>

        <ext-treetable v-loading="loading" ref="treeTable"
                       row-key="title"
                       border
                       :data="tableData"
                       size="mini" stripe style="margin-top: 5px;">
            <el-table-column label="编号" prop="id" align="center" width="60"/>
            <el-table-column label="图标" prop="icon" align="center" width="60">
                <template slot-scope="scope">
                    <d2-icon-svg class="icon" :name="scope.row.icon | iconNameFilter"/>
                </template>
            </el-table-column>
            <el-table-column label="资源名称" prop="title" align="center">
                <template slot-scope="scope">
                    <span>{{scope.row.title}}</span>
                </template>
            </el-table-column>
            <el-table-column label="权限编码" prop="permission" align="center"/>
            <el-table-column label="前端路径" prop="path" align="center"/>
            <el-table-column label="组件路径" prop="component" align="center"/>
            <el-table-column label="请求地址" prop="url" align="center"/>
            <el-table-column label="请求方式" prop="method" align="center"/>
            <el-table-column label="资源类型" prop="type" width="100" align="center"
                             :filters="[{ text: '目录', value: 'DIR' },
                             { text: '模块', value: 'MODULE' },
                             { text: '按钮', value: 'BUTTON' },
                             { text: '接口', value: 'API' }]"
                             :filter-method="filterType">
                <template slot-scope="scope">
                    <el-tag size="mini" :type="scope.row.type | menuTypeFilter">
                        {{scope.row.type | menuTypeValueFilter }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="排序值" prop="sorted" width="120" align="center"/>
            <el-table-column label="创建时间" prop="create_time" width="150" align="center" :show-overflow-tooltip="true"/>

            <el-table-column fixed="right" label="操作" align="center" width="130">
                <template slot-scope="scope">
                    <el-button type="primary" title="添加子级" size="mini" icon="el-icon-plus" circle
                               @click="handleForm({'type':'DIR','open_type':'DEFAULT','sorted': '999','parentId':scope.row.id, icon:'d2-crud'},'create',scope.row)"></el-button>
                    <el-button type="primary" title="编辑" size="mini" icon="el-icon-edit" circle
                               @click="handleForm(scope.row,'update',scope.row)"></el-button>
                    <el-button type="danger" title="删除" :loading="scope.row.delLoading" size="mini"
                               icon="el-icon-delete" circle @click="handleDelete(scope.row)"></el-button>
                </template>
            </el-table-column>
        </ext-treetable>

        <!--对话框（编辑/添加）-->

        <el-dialog
                :title=textMap[dialogStatus]
                :visible.sync="dialogVisible">
            <el-form ref="rechargeForm" :model="activeMenu" label-width="120px">
                <el-form-item label="菜单编号" prop="id" v-if="dialogStatus !== 'create'">
                    <el-input v-model="activeMenu.id"
                              :disabled="dialogStatus !== 'create'">
                    </el-input>
                </el-form-item>
                <el-form-item label="父节点编号" prop="id" v-if="dialogStatus === 'create'">
                    <el-input v-model="activeMenu.parentId"
                              :disabled="true">
                    </el-input>
                </el-form-item>

                <el-form-item label="名称" prop="title">
                    <el-input v-model="activeMenu.title"
                              placeholder="请输入名称">
                    </el-input>
                </el-form-item>
                <el-form-item label="节点编码" prop="name">
                    <el-input v-model="activeMenu.name"
                              placeholder="请输入节点编码（建议以首字母大写作为编码）">
                    </el-input>
                </el-form-item>
                <el-form-item label="路由地址" prop="path">
                    <el-input v-model="activeMenu.path"
                              placeholder="请输入前端路由地址">
                    </el-input>
                </el-form-item>
                <el-form-item label="权限标识" prop="give_fee">
                    <el-input v-model="activeMenu.permission"
                              placeholder="请输入权限标识（英文，不包含特殊字符）">
                    </el-input>
                </el-form-item>
                <el-form-item label="组件地址" prop="give_fee">
                    <el-input v-model="activeMenu.component"
                              placeholder="前端组件地址">
                    </el-input>
                </el-form-item>

                <el-form-item label="选择图标" prop="icon">
                    <d2-icon-svg-select v-model="activeMenu.icon" :user-input="true"/>
                </el-form-item>

                <el-form-item label="打开方式" prop="open_type">
                    <el-select v-model="activeMenu.open_type" placeholder="请选择打开方式">
                        <el-option
                                v-for="item in menuOpenTypeOptions"
                                :key="item.value"
                                :label="item.text"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="排序权重" prop="sorted">
                    <el-input v-model="activeMenu.sorted"
                              placeholder="默认值为999">
                    </el-input>
                </el-form-item>

                <el-form-item label="资源类型" prop="type">
                    <el-select v-model="activeMenu.type" placeholder="请选择资源类型">
                        <el-option
                                v-for="item in menuTypeOptions"
                                :key="item.value"
                                :label="item.text"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item
                        v-if="activeMenu.type === 'API'"
                        label="请求地址" prop="give_fee">
                    <el-input v-model="activeMenu.path"
                              placeholder="请求链接地址（前端路由地址/网络地址）">
                    </el-input>
                </el-form-item>

                <el-form-item
                        v-if="activeMenu.type === 'API'"
                        label="请求方式" prop="give_fee">
                    <el-select v-model="activeMenu.method" placeholder="请选择HTTP请求方式">
                        <el-option
                                v-for="item in httpRequestMethodOptions"
                                :key="item.value"
                                :label="item.value"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item v-if="dialogStatus === 'update'">
                    <el-button type="primary" @click="update" icon="el-icon-check">确认更新</el-button>
                    <el-button @click="onCancel" icon="el-icon-close">取消</el-button>
                </el-form-item>

                <el-form-item v-if="dialogStatus === 'create'">
                    <el-button type="primary" icon="el-icon-circle-plus-outline" @click="save">确认添加</el-button>
                    <el-button @click="onCancel" icon="el-icon-close">取消</el-button>
                </el-form-item>

            </el-form>

        </el-dialog>

    </d2-container>
</template>

<script>
  import { deleteById, save, tree, update } from '@/api/upms/menu'
  import {
    httpRequestMethodOptions,
    menuOpenTypeOptions,
    menuTypeKeyValue,
    menuTypeMap,
    menuTypeOptions
  } from './common'

  const defaultMenu = {
    parentId: undefined,
    name: undefined,
    title: undefined,
    permission: undefined,
    path: undefined,
    url: undefined,
    method: undefined,
    icon: undefined,
    component: undefined,
    sorted: undefined,
    type: undefined,
    open_type: undefined
  }

  export default {
    name: 'upms-menu',

    filters: {
      menuTypeFilter (type) {
        return menuTypeMap[type]
      },
      menuTypeValueFilter (type) {
        return menuTypeKeyValue[type]
      }
    },
    data () {
      return {
        filename: __filename,
        loading: false,
        tableData: [],
        dialogVisible: false,
        dialogStatus: 'create',
        queryParam: {
          name: undefined
        },
        menuTypeOptions: menuTypeOptions,
        menuOpenTypeOptions: menuOpenTypeOptions,
        httpRequestMethodOptions: httpRequestMethodOptions,
        textMap: {
          update: '编辑菜单',
          create: '创建新菜单'
        },
        activeMenu: Object.assign({}, defaultMenu)
      }
    },
    created () {
      this.getList()
    },
    methods: {
      getList () {
        this.loading = true
        tree().then(res => {
          this.tableData = res
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      handleDelete (row) {
        this.$confirm('确定删除【' + row.title + '】及其子菜单的数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$set(row, 'delLoading', true)
          deleteById(row.id).then(() => {
            this.$refs.treeTable.remove(row)
            this.$set(row, 'delLoading', false)
            this.$message({
              dangerouslyUseHTMLString: true,
              message: '删除【' + row.title + '】成功',
              type: 'success'
            })
          })
        })
      },
      handleForm (row, method, parentRow) {
        if (method === 'update') {
          parentRow = parentRow.parent
        }
        this.dialogStatus = method
        this.dialogVisible = true
        this.activeMenu = row
        console.log(this.activeMenu)
      },
      save () {
        //todo 添加验证
        save(this.activeMenu).then(() => {
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.dialogVisible = false
        }).catch(() => {
          this.dialogVisible = false
        })
      },
      update () {
        var self = this
        //todo 添加验证
        let obj = Object.assign({}, self.activeMenu)
        // 删除树扩展的属性
        delete obj._expanded
        delete obj._level
        delete obj._show
        delete obj.children
        delete obj.leaf
        delete obj.parent
        delete obj.label

        update(obj).then(() => {
          this.$message({
            message: '更新成功',
            type: 'success'
          })
          this.dialogVisible = false
        }).catch(() => {
          this.dialogVisible = false
        })
      },
      onCancel () {
        this.dialogVisible = false
      },
      filterType () {

      }
    }
  }
</script>

<style>

    .icon {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 18px;
        height: 18px;
    }

</style>
